package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.bean.GradeBean;
import com.project.bean.LogBean;
import com.project.bean.RoleBean;
import com.project.bean.UserBean;
import com.project.mapper.IGradeMapper;
import com.project.mapper.ILogMapper;
import com.project.mapper.IRoleMapper;
import com.project.mapper.IUserMapper;
import com.project.service.IUserService;
import org.apache.ibatis.annotations.Mapper;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

@Service
@Transactional
public class UserServiceImpl implements IUserService {
    @Autowired
    private IUserMapper userMapper;
    @Autowired
    private IRoleMapper roleMapper;
    @Autowired
    private IGradeMapper gradeMapper;
    @Autowired
    private ILogMapper logMapper;

    @Override
    public UserBean login(String userName, String pwd) {
        //根据输入的用户账号和密码，登录用户。同时查询该用户的权限信息。登录成功后，记录登陆日志
        QueryWrapper<UserBean> qw = new QueryWrapper<>();
        if (userName != null && userName != "") {
            qw.eq("u_userName", userName);
        }
        if (pwd != null && pwd != "") {
            qw.eq("u_pwd", pwd);
        }
        UserBean user = userMapper.selectOne(qw);
        if (user == null) {
            return null;
        }
        user.setRoleList(roleMapper.findRoleListByUserId(user.getUserId()));
        user.setGradeList(gradeMapper.findGradeListByUserId(user.getUserId()));
        Calendar cal = Calendar.getInstance();
        String h = String.valueOf(cal.get(Calendar.HOUR_OF_DAY));
        String mi = String.valueOf(cal.get(Calendar.MINUTE));
        if (h.length() == 1) {
            h = "0" + h;
        }
        if (mi.length() == 1) {
            mi = "0" + mi;
        }
        logMapper.insert(new LogBean("用户" + user.getRelName() + "在" + h + ":" + mi + "登录"));
        return user;
    }

    @Override
    public IPage<UserBean> cutByItem(Integer pageNO, String userName) {
        QueryWrapper<UserBean> qw = new QueryWrapper<>();
        if (userName != null && userName != "") {
            qw.like("u_userName", userName);
        }
        return userMapper.selectPage(new Page<>(pageNO, 3), qw);
    }

    @Override
    public void del(Integer userId) {
        userMapper.del(userId);
    }

    @Override
    public UserBean findByUserId(Integer userId) {
        UserBean user = userMapper.selectById(userId);
        user.setRoleList(roleMapper.findRoleListByUserId(userId));
        user.setGradeList(gradeMapper.findGradeListByUserId(userId));
        return user;
    }

    @Override
    public void updateRole(Integer userId, Integer[] newRoleIdArray) {
        userMapper.updateRole(userId, newRoleIdArray);
    }

    @Override
    public void add(UserBean user, Integer[] roleIdArray) {
        userMapper.insert(user);
        userMapper.updateRole(user.getUserId(), roleIdArray);
    }

    @Override
    public void updatePwd(Integer userId, String newPwd) {
        UserBean user = userMapper.selectById(userId);
        user.setPwd(newPwd);
        userMapper.updateById(user);
    }

    @Override
    public void addUser(UserBean user, Integer[] roleIdArray) {
        QueryWrapper<UserBean> qw = new QueryWrapper<>();
        qw.eq("u_userName", user.getUserName());
        UserBean u = userMapper.selectOne(qw);
        if (u != null) {
            return;
        }

        String salt = this.getSalt();
        Md5Hash md5Hash = new Md5Hash(user.getPwd(), salt, 1024);

        user.setPwd(md5Hash.toHex());
        user.setSalt(salt);
        userMapper.insert(user);
        userMapper.updateRole(user.getUserId(), roleIdArray);
    }

    private String getSalt() {
        char[] array = new char[26];
        for (char i = 'a'; i <= 'z'; i++) {
            array[i - 'a'] = i;
        }
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            sb.append(array[(int) (Math.random() * 26)]);
        }

        return sb.toString();
    }

    @Override
    public UserBean findByName(String name) {
        QueryWrapper<UserBean> qw = new QueryWrapper<>();
        qw.eq("u_userName", name);
        UserBean user = userMapper.selectOne(qw);
        if (user == null) {
            return null;
        }
        user.setRoleList(roleMapper.findRoleListByUserId(user.getUserId()));
        List<GradeBean> list = gradeMapper.findGradeListByUserId(user.getUserId());
        user.setGradeList(list);
        long totalMillsSeconds = System.currentTimeMillis();//总毫秒数  从1970年1月1日开始计算
        String m = String.valueOf((totalMillsSeconds / 1000 / 60) % 60);//当前分钟
        String h = String.valueOf((totalMillsSeconds / 1000 / 60 / 60 + 8) % 24);//当前小时
        if (m.length() == 1) {
            m = "0" + m;
        }
        if (h.length() == 1) {
            h = "0" + h;
        }
        String str = "用户" + user.getUserName() + "在" + h + ":" + m + "登录系统";
        logMapper.insert(new LogBean(str));
        return user;
    }
}
